//
//  CardbagDetailVC.swift
//  CardBag
//
//  Created by hl on 2019/5/21.
//  Copyright © 2019 hlznj. All rights reserved.
//

import UIKit

class CardbagDetailVC: BaseViewController {

    var codeImgView = UIImageView.init()

    var cardbagModel: CardbagModel?


    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = self.cardbagModel?.cardbagName

        var codeType: CodeType?
        if cardbagModel?.cardbagType == "Qr" {
            codeType = .Qr
        } else if cardbagModel?.cardbagType == "bar" {
            codeType = .bar
        } else {
            codeType = .unknown
        }

        self.codeImgView.image = self.generateCode128(code: cardbagModel!.cardbagCode, codeSize: CGSize.init(width: kScreenW-20, height: kScreenW-20), codeType: codeType!)
        self.view.addSubview(self.codeImgView)

        self.codeImgView.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.center.equalTo(self.view)
        }
    }

    func generateCode128(code: String, codeSize: CGSize, codeType: CodeType) -> UIImage {
        let stringData = code.data(using: .utf8)

        //        CIAztecCodeGenerator 二维码
        //        CICode128BarcodeGenerator 条形码
        //        CIPDF417BarcodeGenerator
        //        CIQRCodeGenerator     二维码
        let qrFilter: CIFilter?
        if codeType == .Qr {
            qrFilter = CIFilter(name: "CIQRCodeGenerator")
        } else if codeType == .bar {
            qrFilter = CIFilter(name: "CICode128BarcodeGenerator")
        } else {
            if code.count > 13 {
                qrFilter = CIFilter(name: "CIQRCodeGenerator")
            } else {
                qrFilter = CIFilter(name: "CICode128BarcodeGenerator")
            }
        }
        qrFilter?.setDefaults()
        qrFilter?.setValue(stringData, forKey: "inputMessage")

        var outputImage: CIImage? = qrFilter?.outputImage

        if outputImage == nil {
            qrFilter?.name = "CIQRCodeGenerator"
            outputImage = qrFilter?.outputImage
            if outputImage == nil {
                return UIImage.init()
            }
        }

        let scaleX: CGFloat = codeSize.width/outputImage!.extent.size.width
        let scaleY: CGFloat = codeSize.height/outputImage!.extent.size.height
        let resultImage = outputImage?.transformed(by: CGAffineTransform.init(scaleX: scaleX, y: scaleY))
        let image = UIImage.init(ciImage: resultImage!)
        return image
    }

}
